package com.l024.easyandroidlib.http.observer;

import android.net.ParseException;

import com.l024.easyandroidlib.http.request.RxHttpManager;

import org.json.JSONException;

import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * @Author: Cat
 * @CreateTime: 2022-07-29  11:10
 * @Description: TODO
 * @Version: 1.0
 */
public abstract class BaseObserver<T> implements Observer<T>, ISubscriber<T> {

    /**
     * 是否显示loading
     * @return
     */
    protected boolean isShowLoading() {
        return true;
    }

    /**
     * 标记网络请求的tag
     * tag下的一组或一个请求，用来处理一个页面的所以请求或者某个请求
     * 设置一个tag就行就可以取消当前页面所有请求或者某个请求了
     *
     * @return string
     */
    protected abstract String setTag();

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        RxHttpManager.get().add(setTag(), d);
        doOnSubscribe(d);
    }

    @Override
    public void onNext(@NonNull T t) {
        doOnNext(t);
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof HttpException) {
            //   HTTP错误
            doOnError("HTTP ERROR");
        } else if (e instanceof ConnectException
                || e instanceof UnknownHostException) {
            //   连接错误
            doOnError("HTTP CONNECT ERROR");
        } else if (e instanceof InterruptedIOException) {
            //  连接超时
            doOnError("HTTP CONNECT TIME OUT");
        } else if (e instanceof com.alibaba.fastjson.JSONException
                || e instanceof JSONException
                || e instanceof ParseException) {
            //  解析错误
            doOnError("HTTP PARSING ERROR");
        } else {
            doOnError("HTTP UNKNOWN ERROR");
        }
    }

    @Override
    public void onComplete() {
        doOnCompleted();
    }
}
